// 演示 v1.2.0 版本的使用方法。
package main

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"os"

	"gitee.com/rocket049/gobstream"
)

func main() {
	l, err := net.Listen("tcp", "0.0.0.0:9876")
	if err != nil {
		panic(err)
	}
	defer l.Close()
	for {
		conn, err := l.Accept()
		if err != nil {
			log.Println(err.Error())
			continue
		}
		stream1 := gobstream.NewStreamConn(conn)
		serveStream(stream1)
		conn.Close()
	}
}

var files = make(map[uint32]*os.File)
var datas = make(map[uint32]*bytes.Buffer)

func serveStream(stream *gobstream.StreamConn) error {
	reader, err := stream.BeginReader()
	if err != nil {
		log.Println(err.Error())
		return err
	}
	for data := range reader {
		switch data.Typ {
		case gobstream.DataTypeFile:
			println("receive file: ", data.FileName)
			stream.SendString(data.Session, fmt.Sprintf("receive file:%s\n", data.FileName), false)
		case gobstream.DataTypeByte:
			println("receive str:", string(data.Bytes))
			stream.SendString(data.Session, fmt.Sprintf("receive str:%s\n", string(data.Bytes)), false)
		}
	}
	println("connection closed")
	return nil
}
